﻿create procedure dbo.SavePreferredTakeoutMenu
(
		@Name varchar(200),
		@UserID int,
		@Instructions varchar(2000),
		@MenuItems varchar(1000),
		@PreferredTakeoutMenuID int = null OUTPUT
	)

AS
	
	/* First.  Save Menu Data */
	
	DECLARE @iCount int
	DECLARE @MenuItemID int
	DECLARE @Quantity int
	DECLARE @Pos int
	
	SET @iCount = (SELECT Count(Id) FROM dbo.PreferredTakeoutMenu WHERE Id = @PreferredTakeoutMenuID)
	
	IF @iCount > 0 
		BEGIN
			UPDATE    dbo.PreferredTakeoutMenu
			SET              Name = @Name, Instructions = @Instructions
		END
	ELSE
		BEGIN
			INSERT INTO dbo.PreferredTakeoutMenu
		                      (Name, UserID, Instructions)
			VALUES     (@Name,@UserID,@Instructions)
			
			SET @PreferredTakeoutMenuID = SCOPE_IDENTITY()
		END
	
	
	
	/* Second. Parse the Menu Items and Quantity and insert */
		
		SET @MenuItems = LTRIM(RTRIM(@MenuItems))+ ','
		SET @Pos = CHARINDEX(',', @MenuItems, 1)

		IF REPLACE(@MenuItems, ',', '') <> ''
			BEGIN
				WHILE @Pos > 0
					BEGIN
			
						
						Set @MenuItemID = LTRIM(RTRIM(LEFT(@MenuItems, @Pos -1)))
									
						SET @MenuItems = RIGHT(@MenuItems, LEN(@MenuItems) - @Pos)
						SET @Pos = CHARINDEX(',', @MenuItems, 1)
			
						SET @Quantity = LTRIM(RTRIM(LEFT(@MenuItems, @Pos - 1)))
			
						SET @MenuItems = RIGHT(@MenuItems, LEN(@MenuItems) - @Pos)
						SET @Pos = CHARINDEX(',', @MenuItems, 1)
					
						
						INSERT INTO dbo.PreferredTakeoutMenuItems
						                      (MenuItemID, PreferredTakeoutMenuId, Quantity)
						VALUES     (@MenuItemID,@PreferredTakeoutMenuID,@Quantity)							
						
						
					END
			END	
	
		
	
	RETURN


